<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x justify-between items-center">
          <div class="flex-x gap-4 pt-2">
            <span v-if="showCourseSelect">
              <course-select v-model="query.courseId" @change="handleCourseChange"></course-select>
            </span>
            <span v-if="showCourseSelect">
              <course-section-select v-model="query.sectionId" :courseId="query.courseId"
                                     @change="handleSectionChange"></course-section-select>
            </span>
            <span>
              <vxe-input v-model="query.keyword" clearable :placeholder="'搜索课时名称'" size="medium"
                         @keyup.enter.native="filterByKeyword"></vxe-input>
            </span>
            <span>
              <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
                         :loading="loading">搜索</el-button>
            </span>
          </div>
          <div class="flex-x">
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加课时
            </el-button>
          </div>
        </div>
      </div>

      <!-- Lesson Table -->
      <vxe-table stripe auto-resize :data="lessonList" :loading="loading" :custom-config="tableCustomConfig" ref="table"
                 :row-config="{height: 80}" align="center">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
        <vxe-table-column field="course.courseName" title="课程" min-width="120" align="left">
          <template v-slot="{ row }">
            <div class="flex-y items-start gap-2">
              <span>课程：{{ row.course.courseName }}</span>
              <span>章节：{{ row.section.sectionName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="lessonName" title="视频" min-width="120">
          <template v-slot="{ row }">
            <div class="flex-y flex-center gap-2">
              <el-link :href="row.videoUrl" target="_blank" v-if="row.videoUrl">
                <el-image style="height: 60px"
                          :src="row.videoUrl + '?x-oss-process=video/snapshot,t_1000,f_jpg,h_60,m_fast'" fit="contain">
                  <div slot="error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </el-link>
              <span>{{ row.lessonName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="description" title="介绍" min-width="200" show-overflow></vxe-table-column>
        <vxe-table-column field="duration" title="时长(秒)" width="100"></vxe-table-column>
        <vxe-table-column field="sortOrder" title="排序" width="80">
          <template v-slot="{ row }">
            <sort-order-editor :value="row.sortOrder" @update="(newValue) => handleSortUpdate(row, newValue)"/>
          </template>
        </vxe-table-column>
        <vxe-table-column field="enabled" title="状态" width="260">
          <template v-slot="{ row }">
            <div class="flex-y gap-2 my-4">
              <div class="flex-x flex-center">
                <el-tag :type="row.enabled ? 'success' : 'info'" size="small">
                  {{ row.enabled ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div><span>创建时间：</span><span>{{ row.gmtCreate }}</span></div>
              <div><span>上次修改：</span><span>{{ row.gmtModified }}</span></div>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="资料" width="120" fixed="right">
          <template v-slot="{ row }">
            <div class="table-actions flex-y flex-s gap-2">
              <el-link type="primary" :underline="false" @click="() => {currentLesson = row; handoutDrawerVisible = true}" size="small">
                <span>讲义</span>
                <span><el-badge :value="row.handoutCount" :type="`${row.handoutCount > 0 ? 'primary' : 'danger'}`"></el-badge></span>
              </el-link>
              <el-link type="primary" :underline="false" @click="showWorkQuestionDrawer(row, 'lesson')" size="small">
                <span>课堂练习</span>
                <span><el-badge :value="row.lessonWorkCount" :type="`${row.lessonWorkCount > 0 ? 'primary' : 'info'}`"></el-badge></span>
              </el-link>
              <el-link type="primary" :underline="false" @click="showWorkQuestionDrawer(row, 'home')" size="small">
                <span>课后练习</span>
                <span><el-badge :value="row.homeWorkCount" :type="`${row.homeWorkCount > 0 ? 'primary' : 'info'}`"></el-badge></span>
              </el-link>            
            </div>
          </template>
        </vxe-table-column>

        <vxe-table-column title="操作" width="90" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip  content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip  content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"></el-button>
      </div>

      <!-- Lesson Dialog -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" @close="resetForm">
        <el-form :model="lessonForm" :rules="rules" ref="lessonForm" label-width="100px" @submit.native.prevent>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属课程" prop="courseId">
                <course-select v-model="lessonForm.courseId"></course-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属章节" prop="sectionId">
                <course-section-select v-model="lessonForm.sectionId"
                                       :courseId="lessonForm.courseId"></course-section-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标题" prop="lessonName">
                <el-input class="w-full" v-model="lessonForm.lessonName" @keyup.enter.native="submitForm"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="课时描述" prop="description">
            <Editor :value.sync="lessonForm.description"></Editor>
          </el-form-item>
          <!-- <el-form-item label="视频地址" prop="videoUrl"> -->
          <!-- <el-input v-model="lessonForm.videoUrl" @keyup.enter.native="submitForm"></el-input> -->
          <!-- </el-form-item> -->

          <el-form-item label="状态" prop="enabled">
            <el-switch v-model="lessonForm.enabled"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="currentLesson.lessonName" :visible.sync="videoDialogVisible" width="400px" class="video-dialog"
                 destroy-on-close>
        <aliyun-oss-upload drag progress :show-file-list="false" accept="video/*" type="course_video" @success="handleUploadSuccess"
                           class="w-full">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将视频拖到此处，或 <em>点击上传</em></div>
        </aliyun-oss-upload>
      </el-dialog>

      <el-drawer v-if="handoutDrawerVisible" :visible.sync="handoutDrawerVisible"
         :title="`讲义列表【${currentLesson.lessonName}】`" size="70%">
        <lesson-handout-list :lessonId="currentLesson.id" @count-change="(count)=>{this.currentLesson.handoutCount = count}"></lesson-handout-list>
      </el-drawer>

      <el-drawer v-if="workQuestionDrawerVisible" :visible.sync="workQuestionDrawerVisible"
         :title="`作业习题【${currentLesson.lessonName}】`" size="70%">
        <lesson-work-question-list :lessonId="currentLesson.id" :workType="workQuestionDrawerType" @count-change="handleWorkQuestionCountChange"></lesson-work-question-list>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import api from '@/common/api';
import CourseSelect from '@/components/admin/CourseSelect';
import CourseSectionSelect from "@/components/admin/CourseSectionSelect.vue";
import Editor from '@/components/admin/Editor.vue';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import {DEFAULT_TABLE_CUSTOM_CONFIG} from "@/common/constants";
import AliyunOssUpload from '@/components/admin/AliyunOssUpload.vue';
import LessonHandoutList from './components/LessonHandoutList.vue';
import LessonWorkQuestionList from './components/LessonWorkQuestionList.vue';

export default {
  name: 'LessonList',
  components: {
    CourseSectionSelect,
    CourseSelect,
    Editor,
    SortOrderEditor,
    AliyunOssUpload,
    LessonHandoutList,
    LessonWorkQuestionList
  },
  props: {
    showCourseSelect: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      videoUploadUrl: '', // 视频上传地址，需要后端返回

      // List data
      videoDialogVisible: false,
      handoutDrawerVisible: false,
      workQuestionDrawerVisible: false,
      workQuestionDrawerType: 'lesson',
      currentLesson: {},
      lessonList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10,
        courseId: this.$route.query.courseId || null,
        sectionId: this.$route.query.sectionId || null,
      },

      // Dialog data
      dialogVisible: false,
      dialogTitle: '',
      sectionOptions: [],
      lessonForm: {
        courseId: null,
        sectionId: null,
        lessonName: '',
        description: '',
        videoUrl: '',
        duration: 0,
        sortOrder: 0,
        enabled: true
      },
      rules: {
        courseId: [
          {required: true, message: '请选择所属课程', trigger: 'change'}
        ],
        lessonName: [
          {required: true, message: '请输入课时名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        sectionId: [
          {required: true, message: '请选择所属章节', trigger: 'change'}
        ],
        description: [
          {required: false, message: '请输入课时描述', trigger: 'blur'}
        ],
        videoUrl: [
          {required: true, message: '请输入视频地址', trigger: 'blur'}
        ],
        duration: [
          {required: true, message: '请输入课时时长', trigger: 'blur'}
        ],
        sortOrder: [
          {required: true, message: '请输入排序序号', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getLessonList();
  },
  methods: {
    // Get lesson list
    async getLessonList() {
      try {
        this.loading = true;
        const {data} = await api.admin_getLessonList({
          courseId: this.query.courseId,
          sectionId: this.query.sectionId,
          currentPage: this.query.currentPage,
          limit: this.query.limit,
          keyword: this.query.keyword
        });
        this.lessonList = data.data.records;
        this.total = data.data.total;
      } catch (error) {
        this.$message.error('获取课时列表失败');
      } finally {
        this.loading = false;
      }
    },

    // Handle course change
    handleCourseChange(courseId) {
      this.query.currentPage = 1;
      this.query.sectionId = null;
      this.getLessonList();
    },
    handleSectionChange(sectionId) {
      this.query.currentPage = 1;
      this.query.sectionId = sectionId;
      this.getLessonList();
    },

    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getLessonList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getLessonList();
    },

    // Handle video upload
    showVideoUploadDialog(row) {
      this.currentLesson = row;
      this.videoDialogVisible = true;
    },
    handleUploadSuccess({url}) {
      this.videoDialogVisible = false;
      const data = {
        id: this.currentLesson.id,
        videoUrl: url
      }
      this.doSubmit(data)
    },

    showWorkQuestionDrawer(row, type) {
      this.currentLesson = row;
      this.workQuestionDrawerVisible = true;
      this.workQuestionDrawerType = type;
    },

    handleWorkQuestionCountChange(type, count) {
      this.currentLesson[`${type}WorkCount`] = count;
    },

    // Handle CRUD operations   
    handleAdd() {
      if (!this.query.courseId) {
        this.$message.warning('请先选择课程');
        return;
      }
      this.dialogTitle = '添加课时';
      this.lessonForm = {
        courseId: this.query.courseId,
        sectionId: this.query.sectionId,
        enabled: true
      }
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑课时';
      this.lessonForm = {...row};
      this.dialogVisible = true;
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该课时?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await api.admin_deleteLesson(row.id);
        this.$message.success('删除成功');
        this.getLessonList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },

    async handleSortUpdate(row, newValue) {
      await api.admin_saveLesson({
        id: row.id,
        sortOrder: newValue
      });
      this.getLessonList();
    },

    // Form operations
    submitForm() {
      this.$refs.lessonForm.validate(async (valid) => {
        if (valid) {
          await this.doSubmit(this.lessonForm);
        }
      });
    },

    async doSubmit(data) {
      try {
        this.loading = true;
        await api.admin_saveLesson(data);
        this.$message.success('更新成功');
        this.dialogVisible = false;
        await this.getLessonList();
      } catch (error) {
        this.$message.error('更新失败');
      } finally {
        this.loading = false;
      }
    },

    resetForm() {
      this.$refs.lessonForm?.resetFields();
      this.lessonForm = {
        courseId: null,
        sectionId: null,
        lessonName: '',
        description: '',
        videoUrl: '',
        duration: 0,
        sortOrder: 0,
        enabled: true
      };
    },

    // Filter operations
    filterByKeyword() {
      this.query.currentPage = 1;
      this.getLessonList();
    },

    // Utils
    formatDate(date) {
      return date;
    }
  }
};
</script>

<style scoped>
:deep(.el-input__inner),
:deep(.vxe-input--inner) {
  height: 32px;
  line-height: 32px;
}

.video-dialog :deep(.el-dialog__body) {
  padding: 20px !important;
  padding-top: 0px !important;
}
</style>
